package edu.ustb.eureka.contract;

import edu.ustb.sc.definitions.ContractActionInfo;
import edu.ustb.sc.definitions.ContractPartyInfo;
import edu.ustb.sc.definitions.SpescConditionCheckStatus;
import edu.ustb.sc.definitions.SpescContractTerm;
import edu.ustb.sc.definitions.SpescTermActionQualifierEnum;
import edu.ustb.sc.definitions.TermLogicEnum;

/**
 * term_2: EUREKA must register(ForecastWeather)
 * 	when WEATHER-FORECAST did commit(ForecastWeather)
 * 	while ForecastWeather.rights.useRight.add(EUREKA)
 * 	where response.code = 204
 */
public class RegistrationContractTerm2 extends SpescContractTerm<RegistrationContract> {

	public RegistrationContractParty partyInfo = new RegistrationContractParty("EUREKA");

	public static SpescTermActionQualifierEnum qualifier = SpescTermActionQualifierEnum.Must;

	public static String actionName = "register";

	public RegistrationContractTerm2() {
	}

	public RegistrationContractTerm2(ContractActionInfo actionInfo) {
		this.actionInfo = actionInfo;
	}

	@Override
	public TermLogicEnum getLogic() {
		return TermLogicEnum.Conditional;
	}

	@Override
	public String getTermName() {
		return "term_2";
	}

	@Override
	public SpescTermActionQualifierEnum getQualifier() {
		return qualifier;
	}

	@Override
	public ContractPartyInfo getPartyInfo() {
		return partyInfo;
	}

	/*
	actionArgs[0]: InstanceInfo
	 */
	@Override
	public SpescConditionCheckStatus whenPreCondition(RegistrationContract contract, Object... actionArgs) {
		try {
			String service = actionArgs[0].toString();
			if (service.contains("WEATHER-FORECAST")) {
				ContractActionInfo commitAction = new ContractActionInfo(RegistrationContract.class
						.getDeclaredMethod("commit", String.class),
						new Object[] {service});
				if (contract.isActionDid(commitAction)) {
					return SpescConditionCheckStatus.Yes;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SpescConditionCheckStatus.No;
	}

	@Override
	public SpescConditionCheckStatus wherePostCondition(RegistrationContract contract, Object... param) {
		try {
			int code = (Integer) param[0];
			if (code >= 200 && code < 300) {
				return SpescConditionCheckStatus.Yes;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SpescConditionCheckStatus.No;
	}

	public String getActionName() {
		return actionName;
	}
}
